package com.rollcall;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import javax.sound.sampled.*;

public class TTSUtil {
    // 多平台语音播报实现（无第三方库依赖）
    
    private static CountDownLatch speakLatch;
    
    /**
     * 多平台语音初始化
     */
    //    public static void initialize() {
//        // 这里做一些需要预加载的操作
//        // Windows/Mac系统通常无需初始化特殊内容
//        System.out.println("语音引擎准备就绪（使用系统自带TTS）");
//    }
    public static void initialize() {
        try {
            setSpeechProperties(5, 100);  // 语速: -10到10, 音量: 0到100
        } catch (Exception e) {
            System.err.println("无法设置语音参数: " + e.getMessage());
        }
    }

    // 设置语音特性 (仅Windows PowerShell生效)
    private static void setSpeechProperties(int rate, int volume) throws IOException {
        if (System.getProperty("os.name").contains("Windows")) {
            String command = String.format(
                    "PowerShell -Command \"$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; " +
                            "$speak.Rate = %d; $speak.Volume = %d;\"",
                    rate, volume);
            Runtime.getRuntime().exec(command);
        }
    }
    
    /**
     * 语音播报（阻塞式）
     */
    public static void speak(String text) throws Exception {
        String os = System.getProperty("os.name").toLowerCase();
        
        if (os.contains("win")) {
            // Windows 方案
            windowsSpeak(text);
        } else if (os.contains("mac")) {
            // MacOS 方案
            macSpeak(text);
        } else if (os.contains("nix") || os.contains("nux")) {
            // Linux 方案 (需要espeak)
            linuxSpeak(text);
        } else {
            // 不支持的系统方案
            System.out.println("[" + text + "]");
            throw new UnsupportedOperationException("当前操作系统不支持语音播报");
        }
        
        // 确保语音完成后再继续
        if (speakLatch != null) {
            speakLatch.await();
        }
    }
    
    /**
     * Windows 语音实现
     */
    private static void windowsSpeak(String text) throws IOException {
        speakLatch = new CountDownLatch(1);
        
        // 构建PowerShell命令
        String command = String.format(
            "PowerShell -Command \"Add-Type -AssemblyName System.Speech; " +
            "$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer; " +
            "$speak.Speak('%s');\"", 
            text.replace("'", "''"));
        
        // 异步执行防止卡住主线程
        new Thread(() -> {
            try {
                Process process = Runtime.getRuntime().exec(command);
                process.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                speakLatch.countDown();
            }
        }).start();
    }
    
    /**
     * MacOS 语音实现
     */
    private static void macSpeak(String text) throws IOException {
        speakLatch = new CountDownLatch(1);
        
        new Thread(() -> {
            try {
                Runtime.getRuntime().exec(new String[]{"say", text}).waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                speakLatch.countDown();
            }
        }).start();
    }
    
    /**
     * Linux 语音实现 (需要安装espeak)
     */
    private static void linuxSpeak(String text) throws IOException {
        speakLatch = new CountDownLatch(1);
        
        new Thread(() -> {
            try {
                Runtime.getRuntime().exec(new String[]{"espeak", "-v", "zh", text}).waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                speakLatch.countDown();
            }
        }).start();
    }
    
    /**
     * 释放资源
     */
    public static void shutdown() {
        // 清理Latch
        if (speakLatch != null) {
            speakLatch.countDown();
        }
        System.out.println("语音引擎已释放");
    }

}
